package com.xunfang.demo.servlet3;

import com.xunfang.demo.service.UserService;
import com.xunfang.demo.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {

    UserService userService = new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //1.接收请求数据
        String username = request.getParameter("username");
        String userpwd = request.getParameter("userpwd");
        //判断验证码正确
        //获取用户输入的验证码
        String loginCode = request.getParameter("loginCode");
        //获取session中的验证码，判断是否正确
        String vsCode = (String) request.getSession(false).getAttribute("vsCode");
        if (vsCode==null){
            request.setAttribute("msg","服务端验证码获取错误！");
            request.getRequestDispatcher("index.jsp").forward(request,response);
            //验证失败，不执行下面代码
            return;
        }
        if (!loginCode.equalsIgnoreCase(vsCode)){
            request.setAttribute("msg","验证码错误!");
            request.getRequestDispatcher("index.jsp").forward(request,response);
            //验证失败，不执行下面代码
            return;
        }
        //2.处理数据-调用业务层的方法
        boolean bool = userService.existsUsers(username, userpwd);
        //3.响应结果
        if(bool){
            request.getSession().setAttribute("username",username);
            //转发和重定向都可以 - 登录成功，转发到主页面
            request.getRequestDispatcher("/main").forward(request,response);
        }else{
            //登录失败，回到登录页面
            response.sendRedirect(request.getContextPath()+"/index.jsp?msg=error");
        }

    }
}
